<template>
  <view class="page-container">
    <!-- 业主信息表单 -->
    <view class="content-section">
      <u-form :model="formData" ref="formRef" :rules="rules">
        <!-- 基本信息 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="user" color="#667eea" size="16"></u-icon>
            <text>基本信息</text>
          </view>
          
          
          <!-- 姓名 -->
          <view class="form-item">
            <view class="item-label">
              <text>姓名</text>
              <text class="required">*</text>
            </view>
            <u-input 
              v-model="formData.ownerName"
              placeholder="请输入真实姓名"
              maxlength="50"
              class="form-input"
            ></u-input>
          </view>
          
          <!-- 身份证号 -->
          <view class="form-item">
            <view class="item-label">
              <text>身份证号</text>
              <text class="required">*</text>
            </view>
            <u-input 
              v-model="formData.idCardNumber"
              placeholder="请输入身份证号"
              maxlength="18"
              class="form-input"
            ></u-input>
          </view>
          
          <!-- 手机号 -->
          <view class="form-item">
            <view class="item-label">
              <text>手机号</text>
              <text class="required">*</text>
            </view>
            <u-input 
              v-model="formData.phoneNumber"
              placeholder="请输入手机号"
              maxlength="11"
              class="form-input"
            ></u-input>
          </view>
          
          <!-- 性别 -->
          <view class="form-item">
            <view class="item-label">
              <text>性别</text>
            </view>
            <u-radio-group v-model="formData.gender" placement="row">
              <u-radio name="1" label="男"></u-radio>
              <u-radio name="2" label="女"></u-radio>
            </u-radio-group>
          </view>
          
          <!-- 出生日期 -->
          <view class="form-item">
            <view class="item-label">
              <text>出生日期</text>
            </view>
            <u-datetime-picker
              v-model="formData.birthDate"
              mode="date"
              :min-date="minDate"
              :max-date="maxDate"
              @confirm="onBirthDateConfirm"
              :show-toolbar="true"
              :close-on-click-overlay="true"
            >
              <view class="date-picker-display" @click="() => {}">
                <text v-if="formData.birthDate" class="selected-date">
                  {{ formatDate(formData.birthDate) }}
                </text>
                <text v-else class="placeholder">请选择出生日期</text>
                <u-icon name="calendar" color="#999" size="16"></u-icon>
              </view>
            </u-datetime-picker>
          </view>
        </view>
        
        <!-- 联系信息 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="phone" color="#667eea" size="16"></u-icon>
            <text>联系信息</text>
          </view>
          
          <!-- 邮箱 -->
          <view class="form-item">
            <view class="item-label">
              <text>邮箱</text>
            </view>
            <u-input 
              v-model="formData.email"
              placeholder="请输入邮箱地址（可选）"
              maxlength="100"
              class="form-input"
            ></u-input>
          </view>
          
          <!-- 联系地址 -->
          <view class="form-item">
            <view class="item-label">
              <text>联系地址</text>
            </view>
            <u-input 
              v-model="formData.address"
              placeholder="请输入联系地址（可选）"
              maxlength="500"
              class="form-input"
            ></u-input>
          </view>
        </view>
        
        <!-- 职业信息 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="briefcase" color="#667eea" size="16"></u-icon>
            <text>职业信息</text>
          </view>
          
          <!-- 职业 -->
          <view class="form-item">
            <view class="item-label">
              <text>职业</text>
            </view>
            <u-input 
              v-model="formData.occupation"
              placeholder="请输入职业（可选）"
              maxlength="50"
              class="form-input"
            ></u-input>
          </view>
          
          <!-- 工作单位 -->
          <view class="form-item">
            <view class="item-label">
              <text>工作单位</text>
            </view>
            <u-input 
              v-model="formData.workUnit"
              placeholder="请输入工作单位（可选）"
              maxlength="100"
              class="form-input"
            ></u-input>
          </view>
        </view>
        
        <!-- 紧急联系人 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="account" color="#667eea" size="16"></u-icon>
            <text>紧急联系人</text>
          </view>
          
          <!-- 紧急联系人姓名 -->
          <view class="form-item">
            <view class="item-label">
              <text>紧急联系人姓名</text>
            </view>
            <u-input 
              v-model="formData.emergencyContactName"
              placeholder="请输入紧急联系人姓名（可选）"
              maxlength="50"
              class="form-input"
            ></u-input>
          </view>
          
          <!-- 紧急联系人电话 -->
          <view class="form-item">
            <view class="item-label">
              <text>紧急联系人电话</text>
            </view>
            <u-input 
              v-model="formData.emergencyContactPhone"
              placeholder="请输入紧急联系人电话（可选）"
              maxlength="11"
              class="form-input"
            ></u-input>
          </view>
          
        </view>
        
        <!-- 备注信息 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="file-text" color="#667eea" size="16"></u-icon>
            <text>备注信息</text>
          </view>
          
          <view class="form-item">
            <view class="item-label">
              <text>备注</text>
            </view>
            <u-textarea 
              v-model="formData.remarks"
              placeholder="请输入其他需要说明的信息（可选）"
              maxlength="500"
              :auto-height="true"
              class="form-textarea"
            ></u-textarea>
          </view>
        </view>
        
        <!-- 业主信息保存按钮 -->
        <view class="form-section">
          <u-button 
            type="primary" 
            text="保存业主信息"
            :loading="submitting"
            @click="submitOwnerInfo"
            class="owner-save-btn"
            size="large"
            :custom-style="{
              background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
              border: 'none'
            }"
          ></u-button>
        </view>
        
        <!-- 关联房户信息 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="home" color="#667eea" size="16"></u-icon>
            <text>关联房户信息</text>
          </view>
          
          <!-- 无房户信息提示 -->
          <view v-if="householdList.length === 0" class="no-household-tip">
            <u-icon name="info-circle" color="#999" size="20"></u-icon>
            <text>暂无关联房户信息</text>
          </view>
          
          <view 
            v-for="(household, index) in householdList" 
            :key="household.id"
            class="household-item"
          >
            <view class="household-header">
              <view class="household-title">
                <text class="room-info">{{ getFullAddress(household) }}</text>
                <text class="ownership-type">{{ getOwnershipTypeText(household.ownershipType) }}</text>
                <text v-if="household.isPrimaryOwner" class="primary-owner">主业主</text>
              </view>
              <view class="ownership-ratio">
                <text>产权比例：{{ household.ownershipRatio }}%</text>
              </view>
            </view>
            
            <view class="household-form">
              <!-- 房产证号 -->
              <view class="form-item">
                <view class="item-label">
                  <text>房产证号</text>
                </view>
                <u-input 
                  v-model="household.certificateNumber"
                  placeholder="请输入房产证号"
                  maxlength="100"
                  class="form-input"
                ></u-input>
              </view>
              
              <!-- 房产证日期 -->
              <view class="form-item">
                <view class="item-label">
                  <text>房产证日期</text>
                </view>
                <view class="date-picker-display" @click="openCertificateDatePicker(index)">
                  <text v-if="household.certificateDate" class="selected-date">
                    {{ formatDate(household.certificateDate) }}
                  </text>
                  <text v-else class="placeholder">请选择房产证日期</text>
                  <u-icon name="calendar" color="#999" size="16"></u-icon>
                </view>
                <u-datetime-picker
                  v-model="household.certificateDate"
                  mode="date"
                  :min-date="minDate"
                  :max-date="maxDate"
                  @confirm="(value) => onCertificateDateConfirm(value, index)"
                  @cancel="showCertificateDatePicker[index] = false"
                  :show="showCertificateDatePicker[index]"
                  :show-toolbar="true"
                  :close-on-click-overlay="true"
                ></u-datetime-picker>
              </view>
              
              <!-- 产权开始日期 -->
              <view class="form-item">
                <view class="item-label">
                  <text>产权开始日期</text>
                </view>
                <view class="date-picker-display" @click="openOwnershipStartDatePicker(index)">
                  <text v-if="household.ownershipStartDate" class="selected-date">
                    {{ formatDate(household.ownershipStartDate) }}
                  </text>
                  <text v-else class="placeholder">请选择产权开始日期</text>
                  <u-icon name="calendar" color="#999" size="16"></u-icon>
                </view>
                <u-datetime-picker
                  v-model="household.ownershipStartDate"
                  mode="date"
                  :min-date="minDate"
                  :max-date="maxDate"
                  @confirm="(value) => onOwnershipStartDateConfirm(value, index)"
                  @cancel="showOwnershipStartDatePicker[index] = false"
                  :show="showOwnershipStartDatePicker[index]"
                  :show-toolbar="true"
                  :close-on-click-overlay="true"
                ></u-datetime-picker>
              </view>
              
              <!-- 产权结束日期（适用于部分产权） -->
              <view class="form-item" v-if="household.ownershipType === 3">
                <view class="item-label">
                  <text>产权结束日期</text>
                </view>
                <view class="date-picker-display" @click="openOwnershipEndDatePicker(index)">
                  <text v-if="household.ownershipEndDate" class="selected-date">
                    {{ formatDate(household.ownershipEndDate) }}
                  </text>
                  <text v-else class="placeholder">请选择产权结束日期</text>
                  <u-icon name="calendar" color="#999" size="16"></u-icon>
                </view>
                <u-datetime-picker
                  v-model="household.ownershipEndDate"
                  mode="date"
                  :min-date="minDate"
                  :max-date="maxDate"
                  @confirm="(value) => onOwnershipEndDateConfirm(value, index)"
                  @cancel="showOwnershipEndDatePicker[index] = false"
                  :show="showOwnershipEndDatePicker[index]"
                  :show-toolbar="true"
                  :close-on-click-overlay="true"
                ></u-datetime-picker>
              </view>
              
              <!-- 抵押信息 -->
              <view class="form-item">
                <view class="item-label">
                  <text>抵押信息</text>
                </view>
                <u-textarea 
                  v-model="household.mortgageInfo"
                  placeholder="请输入抵押信息（可选）"
                  maxlength="500"
                  :auto-height="true"
                  class="form-textarea"
                ></u-textarea>
              </view>
              
              <!-- 房户备注 -->
              <view class="form-item">
                <view class="item-label">
                  <text>房户备注</text>
                </view>
                <u-textarea 
                  v-model="household.remark"
                  placeholder="请输入房户相关备注（可选）"
                  maxlength="500"
                  :auto-height="true"
                  class="form-textarea"
                ></u-textarea>
              </view>
            </view>
            
            <!-- 房户信息保存按钮 -->
            <view class="household-save-section">
              <u-button 
                type="primary" 
                text="保存房户信息"
                :loading="householdSaving[index]"
                @click="submitHouseholdInfo(index)"
                class="household-save-btn"
                size="normal"
                :custom-style="{
                  background: 'linear-gradient(135deg, #2ed573 0%, #27ae60 100%)',
                  border: 'none'
                }"
              ></u-button>
            </view>
          </view>
        </view>
      </u-form>
    </view>

  </view>
</template>

<script setup>
/**
 * 业主信息完善页面
 * @author Wu.Liang
 * @date 2025-01-21
 * @version 1.0 - 根据sc_owner表结构设计业主信息完善功能
 */

import { ref, reactive, onMounted } from 'vue'
import { ownerApi, ownerHouseholdApi } from '@/api/property'
import { useAuthStore } from '@/store'

// 表单数据
const formData = reactive({
  ownerName: '',
  idCardNumber: '',
  phoneNumber: '',
  gender: '1',
  birthDate: '',
  email: '',
  occupation: '',
  workUnit: '',
  emergencyContactName: '',
  emergencyContactPhone: '',
  address: '',
  remarks: ''
})

// 房户列表数据
const householdList = ref([])

// 表单验证规则
const rules = {
  ownerName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 100, message: '姓名长度在2到100个字符', trigger: 'blur' }
  ],
  idCardNumber: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  emergencyContactPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的紧急联系人电话', trigger: 'blur' }
  ]
}

// 日期范围
const minDate = new Date('1900-01-01').getTime()
const maxDate = new Date().getTime()

// 提交状态
const submitting = ref(false)
const householdSaving = ref([])

// 表单引用
const formRef = ref(null)

// 日期选择器显示状态
const showCertificateDatePicker = ref([])
const showOwnershipStartDatePicker = ref([])
const showOwnershipEndDatePicker = ref([])

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  
  // 处理不同类型的日期数据
  let date
  if (typeof timestamp === 'object' && timestamp.value) {
    // 处理对象类型的日期（如 {value: 1234567890}）
    date = new Date(timestamp.value)
  } else if (typeof timestamp === 'string' || typeof timestamp === 'number') {
    // 处理字符串或数字类型的日期
    date = new Date(timestamp)
  } else {
    console.warn('无效的日期格式:', timestamp)
    return ''
  }
  
  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    console.warn('日期解析失败:', timestamp)
    return ''
  }
  
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 格式化日期为API需要的格式（yyyy-MM-dd）
const formatDateForApi = (timestamp) => {
  if (!timestamp) return null
  
  // 处理不同类型的日期数据
  let date
  if (typeof timestamp === 'object' && timestamp.value) {
    // 处理对象类型的日期（如 {value: 1234567890}）
    date = new Date(timestamp.value)
  } else if (typeof timestamp === 'string') {
    // 如果已经是字符串格式，直接返回
    if (timestamp.match(/^\d{4}-\d{2}-\d{2}$/)) {
      return timestamp
    }
    date = new Date(timestamp)
  } else if (typeof timestamp === 'number') {
    // 处理数字类型的日期
    date = new Date(timestamp)
  } else {
    console.warn('无效的日期格式:', timestamp)
    return null
  }
  
  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    console.warn('日期解析失败:', timestamp)
    return null
  }
  
  // 返回yyyy-MM-dd格式的字符串
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 解析日期为时间戳，确保日期有效
const parseDateToTimestamp = (dateValue) => {
  if (!dateValue) return ''
  
  try {
    let date
    if (typeof dateValue === 'string') {
      // 处理字符串格式的日期
      if (dateValue.match(/^\d{4}-\d{2}-\d{2}$/)) {
        // 已经是yyyy-MM-dd格式
        date = new Date(dateValue)
      } else {
        // 其他字符串格式
        date = new Date(dateValue)
      }
    } else if (typeof dateValue === 'number') {
      // 处理数字格式的日期
      date = new Date(dateValue)
    } else {
      console.warn('不支持的日期格式:', dateValue)
      return ''
    }
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      console.warn('日期解析失败:', dateValue)
      return ''
    }
    
    // 检查日期是否在合理范围内（1900-2100年）
    const year = date.getFullYear()
    if (year < 1900 || year > 2100) {
      console.warn('日期超出合理范围:', dateValue, '年份:', year)
      return ''
    }
    
    return date.getTime()
  } catch (error) {
    console.error('日期解析异常:', error, '原始值:', dateValue)
    return ''
  }
}

// 出生日期确认
const onBirthDateConfirm = (value) => {
  formData.birthDate = value
}

// 房产证日期确认
const onCertificateDateConfirm = (value, index) => {
  // 确保日期值是时间戳格式
  householdList.value[index].certificateDate = typeof value === 'object' && value.value ? value.value : value
  showCertificateDatePicker.value[index] = false
}

// 产权开始日期确认
const onOwnershipStartDateConfirm = (value, index) => {
  // 确保日期值是时间戳格式
  householdList.value[index].ownershipStartDate = typeof value === 'object' && value.value ? value.value : value
  showOwnershipStartDatePicker.value[index] = false
}

// 产权结束日期确认
const onOwnershipEndDateConfirm = (value, index) => {
  // 确保日期值是时间戳格式
  householdList.value[index].ownershipEndDate = typeof value === 'object' && value.value ? value.value : value
  showOwnershipEndDatePicker.value[index] = false
}

// 打开房产证日期选择器
const openCertificateDatePicker = (index) => {
  // 初始化显示状态数组
  if (!showCertificateDatePicker.value[index]) {
    showCertificateDatePicker.value[index] = false
  }
  showCertificateDatePicker.value[index] = true
}

// 打开产权开始日期选择器
const openOwnershipStartDatePicker = (index) => {
  // 初始化显示状态数组
  if (!showOwnershipStartDatePicker.value[index]) {
    showOwnershipStartDatePicker.value[index] = false
  }
  showOwnershipStartDatePicker.value[index] = true
}

// 打开产权结束日期选择器
const openOwnershipEndDatePicker = (index) => {
  // 初始化显示状态数组
  if (!showOwnershipEndDatePicker.value[index]) {
    showOwnershipEndDatePicker.value[index] = false
  }
  showOwnershipEndDatePicker.value[index] = true
}

// 获取产权类型文本
const getOwnershipTypeText = (type) => {
  const typeMap = {
    1: '完全产权',
    2: '共有产权',
    3: '部分产权'
  }
  return typeMap[type] || '未知'
}

// 获取完整地址信息
const getFullAddress = (household) => {
  const parts = []
  
  // 添加社区名
  if (household.communityName) {
    parts.push(household.communityName)
  }
  
  // 添加楼栋名
  if (household.buildingName) {
    parts.push(household.buildingName)
  }
  
  // 添加单元名
  if (household.unitName) {
    parts.push(household.unitName)
  }
  
  // 添加房号
  if (household.roomNumber) {
    parts.push(household.roomNumber)
  }
  
  // 如果没有任何地址信息，返回默认值
  if (parts.length === 0) {
    return '地址信息不完整'
  }
  
  return parts.join(' ')
}


// 提交业主信息
const submitOwnerInfo = async () => {
  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) {
      return
    }
    
    submitting.value = true
    
    // 准备提交数据，只包含业主基本信息
    const submitData = {
      ownerName: formData.ownerName,
      idCard: formData.idCardNumber,
      phone: formData.phoneNumber,
      gender: parseInt(formData.gender),
      birthDate: formData.birthDate,
      email: formData.email,
      occupation: formData.occupation,
      company: formData.workUnit,
      emergencyContact: formData.emergencyContactName,
      emergencyPhone: formData.emergencyContactPhone,
      address: formData.address,
      remark: formData.remarks
    }
    
    console.log('提交业主信息:', submitData)
    
    // 调用API保存业主信息
    const response = await ownerApi.saveOwnerInfo(submitData)
    console.log('保存业主信息响应:', response)
    
    if (response && response.code === 200) {
      uni.showToast({
        title: '业主信息保存成功',
        icon: 'success'
      })
      
      // 保存成功后重新加载数据
      await loadOwnerInfo()
    } else {
      uni.showToast({
        title: response?.message || '保存失败，请重试',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('保存业主信息失败:', error)
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 提交房户信息
const submitHouseholdInfo = async (index) => {
  try {
    const household = householdList.value[index]
    if (!household) {
      uni.showToast({
        title: '房户信息不存在',
        icon: 'none'
      })
      return
    }
    
    // 检查是否有关联ID
    if (!household.id) {
      uni.showToast({
        title: '房户关联信息不完整',
        icon: 'none'
      })
      return
    }
    
    // 设置当前房户的保存状态
    householdSaving.value[index] = true
    
    // 准备提交数据，只包含房户关联信息
    const submitData = {
      ownerId: household.ownerId, // 如果有的话
      householdId: household.householdId,
      ownershipType: household.ownershipType,
      ownershipRatio: household.ownershipRatio,
      // 确保日期字段是yyyy-MM-dd格式的字符串
      ownershipStartDate: household.ownershipStartDate ? formatDateForApi(household.ownershipStartDate) : null,
      ownershipEndDate: household.ownershipEndDate ? formatDateForApi(household.ownershipEndDate) : null,
      isPrimaryOwner: household.isPrimaryOwner,
      certificateNumber: household.certificateNumber,
      certificateDate: household.certificateDate ? formatDateForApi(household.certificateDate) : null,
      mortgageInfo: household.mortgageInfo,
      remark: household.remark
    }
    
    console.log('提交房户信息:', submitData)
    
    // 调用API更新房户关联信息
    const response = await ownerHouseholdApi.updateOwnerHousehold(household.id, submitData)
    console.log('保存房户信息响应:', response)
    
    if (response && response.code === 200) {
      uni.showToast({
        title: '房户信息保存成功',
        icon: 'success'
      })
      
      // 保存成功后重新加载数据
      await loadOwnerInfo()
    } else {
      uni.showToast({
        title: response?.message || '保存失败，请重试',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('保存房户信息失败:', error)
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none'
    })
  } finally {
    householdSaving.value[index] = false
  }
}

// 提交表单（保留原函数，用于兼容性，现在只保存业主基本信息）
const submitForm = async () => {
  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) {
      return
    }
    
    submitting.value = true
    
    // 准备提交数据，只包含业主基本信息
    const submitData = {
      ownerName: formData.ownerName,
      idCard: formData.idCardNumber,
      phone: formData.phoneNumber,
      gender: parseInt(formData.gender),
      birthDate: formData.birthDate,
      email: formData.email,
      occupation: formData.occupation,
      company: formData.workUnit,
      emergencyContact: formData.emergencyContactName,
      emergencyPhone: formData.emergencyContactPhone,
      address: formData.address,
      remark: formData.remarks
    }
    
    console.log('提交数据:', submitData)
    
    // 调用API保存业主信息
    const response = await ownerApi.saveOwnerInfo(submitData)
    console.log('保存响应:', response)
    
    if (response && response.code === 200) {
      uni.showToast({
        title: '信息保存成功',
        icon: 'success'
      })
      
      // 保存成功后重新加载数据
      await loadOwnerInfo()
      
      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    } else {
      uni.showToast({
        title: response?.message || '保存失败，请重试',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('保存业主信息失败:', error)
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 加载现有业主信息
const loadOwnerInfo = async () => {
  try {
    console.log('开始加载业主信息...')
    
    // 使用区域服务的移动端接口获取当前用户业主信息
    const response = await ownerApi.getOwnerInfo()
    console.log('业主信息API响应:', response)
    
    if (response && response.code === 200 && response.data) {
      const ownerData = response.data
      console.log('业主数据:', ownerData)
      
      // 填充基本信息
      Object.assign(formData, {
        ownerName: ownerData.ownerName || '',
        idCardNumber: ownerData.idCard || '',
        phoneNumber: ownerData.phone || '',
        gender: ownerData.gender ? ownerData.gender.toString() : '1',
        birthDate: ownerData.birthDate || '',
        email: ownerData.email || '',
        occupation: ownerData.occupation || '',
        workUnit: ownerData.company || '',
        emergencyContactName: ownerData.emergencyContact || '',
        emergencyContactPhone: ownerData.emergencyPhone || '',
        address: ownerData.address || '',
        remarks: ownerData.remark || ''
      })
      
      // 填充房户信息
      if (ownerData.householdList && ownerData.householdList.length > 0) {
        console.log('房户信息:', ownerData.householdList)
        householdList.value = ownerData.householdList.map(household => ({
          id: household.id,
          householdId: household.householdId,
          roomNumber: household.roomNumber,
          communityName: household.communityName,
          buildingName: household.buildingName,
          unitName: household.unitName,
          ownershipType: household.ownershipType,
          ownershipRatio: household.ownershipRatio,
          // 确保日期字段是正确的时间戳格式，避免无效日期
          ownershipStartDate: household.ownershipStartDate ? parseDateToTimestamp(household.ownershipStartDate) : '',
          ownershipEndDate: household.ownershipEndDate ? parseDateToTimestamp(household.ownershipEndDate) : '',
          isPrimaryOwner: household.isPrimaryOwner,
          certificateNumber: household.certificateNumber || '',
          certificateDate: household.certificateDate ? parseDateToTimestamp(household.certificateDate) : '',
          mortgageInfo: household.mortgageInfo || '',
          remark: household.remark || ''
        }))
        console.log('处理后的房户列表:', householdList.value)
      } else {
        console.log('暂无房户信息')
        householdList.value = []
      }
      
      console.log('业主信息加载完成')
    } else {
      console.log('未找到业主信息或用户未关联业主')
      // 如果用户未关联业主，显示空表单供用户填写
    }
  } catch (error) {
    console.error('加载业主信息失败:', error)
    uni.showToast({
      title: '加载业主信息失败',
      icon: 'none'
    })
  }
}

onMounted(() => {
  loadOwnerInfo()
})
</script>

<style lang="scss" scoped>
/* 页面容器 - 必须完全顶满手机宽度 */
.page-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  padding-bottom: 120rpx;
}

.intro-section {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  padding: 40rpx 30rpx;
  margin-bottom: 20rpx;
  
  .intro-content {
    display: flex;
    align-items: center;
    gap: 20rpx;
    
    .intro-text {
      color: white;
      font-size: 28rpx;
      font-weight: 500;
      line-height: 1.4;
    }
  }
}

/* 内容区域 - 确保无左右空白 */
.content-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 16px;
  margin: 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 表单区块 - 统一的间距和样式 */
.form-section {
  margin-bottom: 24px;
  
  .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
    font-size: 15px;
    font-weight: 600;
    color: #333;
    
    .required {
      color: #f56c6c;
      font-weight: bold;
    }
  }
}

.form-item {
  margin-bottom: 30rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .item-label {
    display: flex;
    align-items: center;
    gap: 8rpx;
    margin-bottom: 16rpx;
    
    text {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }
    
    .required {
      color: #ff4757;
      font-size: 24rpx;
    }
  }
}

.form-input {
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 2rpx solid #e9ecef;
  transition: all 0.3s ease;
  
  &:focus-within {
    border-color: #667eea;
    background: white;
  }
}

.form-textarea {
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 2rpx solid #e9ecef;
  min-height: 120rpx;
  transition: all 0.3s ease;
  
  &:focus-within {
    border-color: #667eea;
    background: white;
  }
}

.date-picker-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  transition: all 0.3s ease;
  min-height: 48px;
  width: 100%;
  box-sizing: border-box;
  cursor: pointer;
  
  &:hover {
    border-color: #667eea;
    background: white;
  }
  
  &:active {
    border-color: #667eea;
    background: white;
  }
  
  .selected-date {
    color: #333;
    font-size: 14px;
    flex: 1;
  }
  
  .placeholder {
    color: #999;
    font-size: 14px;
    flex: 1;
  }
  
  .u-icon {
    margin-left: 8px;
    flex-shrink: 0;
  }
}

.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 20rpx 30rpx;
  border-top: 2rpx solid #f0f0f0;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .submit-btn {
    width: 100%;
    height: 88rpx;
    border-radius: 44rpx;
    border: none;
    font-size: 32rpx;
    font-weight: 600;
  }
}

/* 小屏幕适配 */
@media screen and (max-width: 375px) {
  .content-section {
    padding: 12px;
  }
  
  .form-section {
    margin-bottom: 20px;
  }
  
  .intro-section {
    padding: 30rpx 20rpx;
  }
  
  .submit-section {
    padding: 15rpx 20rpx;
  }
}

/* 大屏幕适配 */
@media screen and (min-width: 414px) {
  .content-section {
    padding: 20px;
  }
}

@media screen and (min-width: 769px) {
  .page-container {
    max-width: 800px;
    margin: 0 auto;
  }
}

/* 房户信息样式 */
.household-item {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  border: 2rpx solid #e9ecef;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.household-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #e9ecef;
}

.household-title {
  display: flex;
  align-items: center;
  gap: 12rpx;
  
  .room-info {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }
  
  .ownership-type {
    font-size: 24rpx;
    color: #667eea;
    background: rgba(102, 126, 234, 0.1);
    padding: 4rpx 12rpx;
    border-radius: 12rpx;
  }
  
  .primary-owner {
    font-size: 24rpx;
    color: #f56c6c;
    background: rgba(245, 108, 108, 0.1);
    padding: 4rpx 12rpx;
    border-radius: 12rpx;
  }
}

.ownership-ratio {
  font-size: 24rpx;
  color: #666;
}

.household-form {
  .form-item {
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

/* 无房户信息提示样式 */
.no-household-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  padding: 40rpx 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 2rpx dashed #e9ecef;
  
  text {
    font-size: 28rpx;
    color: #999;
  }
}

/* 按钮样式 */
.owner-save-btn {
  width: 100%;
  margin: 20rpx 0;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 600;
  box-shadow: 0 8rpx 16rpx rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
  
  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 4rpx 8rpx rgba(102, 126, 234, 0.3);
  }
}

.household-save-section {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 2rpx solid #e9ecef;
}

.household-save-btn {
  width: 100%;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 600;
  box-shadow: 0 6rpx 12rpx rgba(46, 213, 115, 0.3);
  transition: all 0.3s ease;
  
  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 3rpx 6rpx rgba(46, 213, 115, 0.3);
  }
}
</style>
